package com.maxlen.order.interceptor;

import com.maxlen.common.constant.LoginConstant;
import com.maxlen.common.utils.JwtUtils;
import com.maxlen.common.utils.R;
import com.maxlen.common.utils.ResponseUtils;
import com.maxlen.common.utils.ResultCode;
import com.maxlen.order.entity.to.LoginInfoTO;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static ThreadLocal<LoginInfoTO> threadLocalID = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        List<String> path = new ArrayList<>();
        path.add("/order/order/**");
        path.add("/order/orderitem/**");
        boolean match = false;
        for (String s : path) {
            if(new AntPathMatcher().match(s, request.getRequestURI())) {
                match = true;
            }
        }
//        boolean match = new AntPathMatcher().match("/order/order/status/**", request.getRequestURI());
        if(match){
            return true;
        }

        String header = request.getHeader(LoginConstant.TOKEN);
        if(StringUtils.hasText(header)){
            if(JwtUtils.checkToken(header)){
                String id = JwtUtils.getMemberIdByJwtToken(header);
                if(StringUtils.hasText(id)){
                    String s = stringRedisTemplate.opsForValue().get(LoginConstant.MEMBER_LOGIN + id);
                    if(StringUtils.hasText(s)){
                        LoginInfoTO loginInfoTO = new LoginInfoTO();
                        loginInfoTO.setMemberId(Long.valueOf(id));
                        loginInfoTO.setMemberName(JwtUtils.getMemberAccountByJwtToken(header));
                        threadLocalID.set(loginInfoTO);

                        return true;
                    }else{
                        ResponseUtils.out(response, R.error(ResultCode.USER_ACCOUNT_EXPIRED));
                        return false;
                    }
                }
            }
        }
        ResponseUtils.out(response, R.error(ResultCode.USER_NOT_LOGIN));
        return false;
    }
}
